/**
 * 
 */
package wpmp.security.mgr.task.init.table;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.stereotype.Component;

import wcommons.lang.DateUtils;
import wpmp.security.mgr.SqlStatics;
import wpmp.security.mgr.Statics;
import wpmp.security.mgr.task.BaseTask;

/**
 * @author Wayne.Wang<5waynewang@gmail.com>
 * @since 3:07:57 PM May 6, 2014
 */
@Component
@Lazy(false)
public class InitOrgTableTask extends BaseTask {

	private JdbcTemplate jdbcTemplate;

	@Autowired
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@PostConstruct
	@Override
	public void init() {
		if (log.isInfoEnabled()) {
			log.info("Start to init table[sys_org]");
		}

		final Timestamp currentTime = DateUtils.newTimestamp();

		jdbcTemplate.execute(SqlStatics.INSERT_ROOT_ORG, new PreparedStatementCallback<Integer>() {
			@Override
			public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
				int index = 0;
				ps.setLong(++index, Statics.ROOT_ID);
				ps.setString(++index, Statics.ROOT_NAME);
				ps.setString(++index, Statics.ROOT_LEVEL);
				ps.setTimestamp(++index, currentTime);
				ps.setString(++index, Statics.ROOT);
				ps.setTimestamp(++index, currentTime);
				ps.setString(++index, Statics.ROOT);
				ps.setLong(++index, Statics.ROOT_ID);
				return ps.executeUpdate();
			}
		});

		jdbcTemplate.execute(SqlStatics.INSERT_ORG, new PreparedStatementCallback<Integer>() {
			@Override
			public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
				int index = 0;
				ps.setLong(++index, Statics.UNGROUPED_ID);
				ps.setString(++index, Statics.UNGROUPED_NAME);
				ps.setString(++index, Statics.UNGROUPED_LEVEL);
				ps.setLong(++index, Statics.ROOT_ID);
				ps.setTimestamp(++index, currentTime);
				ps.setString(++index, Statics.ROOT);
				ps.setTimestamp(++index, currentTime);
				ps.setString(++index, Statics.ROOT);
				ps.setLong(++index, Statics.UNGROUPED_ID);
				return ps.executeUpdate();
			}
		});

		if (log.isInfoEnabled()) {
			log.info("Success to init table[sys_org]");
		}
	}

	@PreDestroy
	@Override
	public void destroy() {

	}

}
